<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客流趋势分析 - Apache ECharts 示例</title>
    <link rel="stylesheet" href="css/style.css?v=1.1">
</head>

<body>
    <div class="navbar">
        <a href="index.html">首页</a>
        <a href="traffic_trend.html">客流趋势分析</a>
        <a href="station_ranking.html">站点客流排行</a>
        <a href="funnel_analysis.html">线路站点客流分析</a>
        <a href="line_comparison.html">线路客流量对比</a>
        <a href="transfer_heatmap.html">换乘热度分析</a>
        <a href="poi_analysis.html">站点周边客流特征</a>
        <a href="anomaly_detection.html">异常客流检测</a>
        <a href="od_analysis.html">路径OD分析</a>
        <a href="stop_frequency_usage_analysis.html">站停频率分析</a>
        <a href="dispatch_suggestion.html">智能调度模型</a>
    </div>
    <div class="page-container">
        <div class="chart-header">
            <h2 class="chart-title">不同时间段客流趋势分析</h2>
            <p class="chart-description">
                此图表展示了全天24小时内，公交和地铁的客流（上车和下车人数）变化趋势。通过观察不同时段的客流波动，可以识别出早晚高峰、平峰和夜间等客流特征，为运力调度和线路优化提供数据支持。例如，可以看出通勤高峰期（如早上7-9点和下午5-7点）客流量显著上升。
            </p>
        </div>
        <div class="kpi-cards-container">
            <div class="kpi-card">
                <h4>今日总客流量</h4>
                <p id="total-traffic">--</p>
            </div>
            <div class="kpi-card">
                <h4>早高峰峰值</h4>
                <p id="morning-peak">--</p>
            </div>
            <div class="kpi-card">
                <h4>晚高峰峰值</h4>
                <p id="evening-peak">--</p>
            </div>
            <div class="kpi-card">
                <h4>最繁忙时段</h4>
                <p id="busiest-period">--</p>
            </div>
        </div>
        <div id="traffic-trend-chart" class="chart-container"></div>
    </div>

    <script src="js/echarts.min.js"></script>
    <script type="text/javascript">
        console.log('Script started!');
        // 基于准备好的dom，初始化echarts实例 (客流趋势分析)
        var trafficTrendChart = echarts.init(document.getElementById('traffic-trend-chart'));

        // 从后端API获取数据
        fetch('http://localhost:8081/api/traffic/hourly_trends')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Raw data from API:', data);

                // 初始化小时标签、上车和下车数据数组
                var hours = Array.from({ length: 24 }, (_, i) => (i < 10 ? '0' : '') + i + ':00');
                var onboardData = new Array(24).fill(0);
                var offboardData = new Array(24).fill(0);

                // 遍历从API获取的数据，填充到对应的数组位置
                data.forEach(item => {
                    if (item.hour >= 0 && item.hour < 24) {
                        onboardData[item.hour] = item.onboard;
                        offboardData[item.hour] = item.offboard;
                    }
                });

                // --- KPI Card Calculations ---
                // 1. Total Traffic
                const totalTraffic = onboardData.reduce((sum, current) => sum + current, 0);

                // 2. Morning Peak (e.g., 6 AM - 10 AM)
                const morningHoursData = onboardData.slice(6, 11);
                const morningPeakValue = Math.max(...morningHoursData);

                // 3. Evening Peak (e.g., 4 PM - 8 PM)
                const eveningHoursData = onboardData.slice(16, 21);
                const eveningPeakValue = Math.max(...eveningHoursData);

                // 4. Busiest Period
                const maxTraffic = Math.max(...onboardData);
                const busiestHour = onboardData.indexOf(maxTraffic);
                const busiestPeriodString = `${busiestHour.toString().padStart(2, '0')}:00 - ${(busiestHour + 1).toString().padStart(2, '0')}:00`;

                // Update KPI Card DOM elements
                document.getElementById('total-traffic').innerText = totalTraffic.toLocaleString();
                document.getElementById('morning-peak').innerText = morningPeakValue > 0 ? morningPeakValue.toLocaleString() : 'N/A';
                document.getElementById('evening-peak').innerText = eveningPeakValue > 0 ? eveningPeakValue.toLocaleString() : 'N/A';
                document.getElementById('busiest-period').innerText = busiestPeriodString;
                // --- End of KPI Card Calculations ---

                console.log('Processed hours:', hours);
                console.log('Processed onboardData:', onboardData);
                console.log('Processed offboardData:', offboardData);

                var trafficTrendOption = {
                    title: {
                        text: '不同时间段客流趋势分析',
                        left: 'center',
                        textStyle: {
                            color: '#333',
                            fontSize: 20
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: ['上车', '下车'],
                        top: 'bottom'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: hours,
                        axisLabel: {
                            interval: 2,
                            rotate: 30
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '客流量 (人次)'
                    },
                    series: [
                        {
                            name: '上车',
                            type: 'line',
                            smooth: true,
                            data: onboardData,
                            areaStyle: {}
                        },
                        {
                            name: '下车',
                            type: 'line',
                            smooth: true,
                            data: offboardData,
                            areaStyle: {}
                        }
                    ]
                };

                trafficTrendChart.setOption(trafficTrendOption);
            })
            .catch(error => {
                console.error('Error fetching hourly traffic data:', error);
                // Optionally, could add a message to the user on the chart or page.
            });

        window.addEventListener('resize', function () {
            trafficTrendChart.resize();
        });
    </script>
    <script src="js/common.js"></script>
</body>

</html>